package com.github.baichuan.iot.gateway.restful;

import com.github.baichuan.iot.gateway.context.DeviceContext;
import com.github.baichuan.iot.gateway.context.DeviceContextCache;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/tbox")
@Slf4j
public class DeviceController {
    @Autowired
    private DeviceContextCache cache;

    @PostMapping("/{device}/refresh")
    public ResponseEntity refresh(@PathVariable("device") String device){
        if(cache.contains(device)){
            cache.refresh(device);
            DeviceContext context = cache.get(device);

            log.info("device {} is noticed refresh context, new context is {}", device, context);
            return ResponseEntity.ok("终端信息刷新成功");
        }

        return ResponseEntity.ok("终端不在线无需刷新");
    }

    @PostMapping("/{device}/evict")
    public ResponseEntity evict(@PathVariable("device") String device){
        if(cache.contains(device)){
            DeviceContext context = cache.get(device);
            Channel channel = context.getChannel().get();
            if(channel != null){
                channel.close();
                log.info("终端{}被强制离线", device);
            }
            cache.evict(device);
            return ResponseEntity.ok("操作成功，终端连接已断开");
        } else {
            return ResponseEntity.ok("操作成功，终端不在线");
        }
    }
}
